package com.zz.hhbl.utils

import android.os.Environment
import java.io.File

/**
 * Copyright © 2025 zhun All rights reserved.
 * Created by ZhaoZhun on 2025/3/3 11:08.
 * @author: ZhaoZhun 1820022519@qq.com
 * @version: V1.0
 */
object LocalUrlUtils {
    private const val CACHE_DIR = "hhCache"
    fun getLocalFolderPath(): String {
        val  rootDir = Environment.getExternalStorageDirectory().path + "/" + Environment.DIRECTORY_DOWNLOADS
        val file = File(rootDir, CACHE_DIR)
        if (file.exists().not()){
            file.mkdirs()
        }
        return file.absolutePath
    }

    /**
     * 存在就使用本地地址，不存在就使用 url
     */
    fun getLocalUrl(url: String): String {
        if (isLocalExists(url)) {
            return getLocalPathByUrl(url)
        } else {
            return url
        }
    }

    fun getLocalPathByUrl(url: String): String {
        val fileName = if (url.isNullOrEmpty()) "" else url.substring(url.lastIndexOf('/') + 1)
        return getLocalFolderPath() + "/" + fileName
    }

    fun getFileNameByUrl(url: String): String {
        if (url.isNullOrEmpty()) return ""
        val fileName = url.substring(url.lastIndexOf('/') + 1)
        return fileName
    }

    fun isLocalExists(url: String): Boolean {
        return File(getLocalPathByUrl(url)).exists()
    }
}